package com.zhaoyh.controller;

import com.zhaoyh.bean.Userinfo;
import com.zhaoyh.framework.code.util.WebContextUtil;
import com.zhaoyh.service.UserinfoService;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

public class BaseController {

    /**
     * 生成视图，用于继承
     * @param view
     */
    protected ModelAndView innerCreateModelAndView (String view, Object... objects) {
        assert (objects.length % 2) == 0;
        Map<String, Object> modelMap = new HashMap<String, Object>();
        for (int i = 0; i < objects.length; i++) {
            String name = (String) objects[i++];
            modelMap.put(name, objects[i]);
        }
        return new ModelAndView(view, modelMap);
    }

    /**
     * 通过PrintWriter将响应数据写入response，ajax可以接受到这个数据
     *
     * @param response
     * @param data
     */
    protected void renderData(HttpServletResponse response, String data) {
        PrintWriter printWriter = null;
        try {
            response.setContentType("text/html; charset=utf-8");
            printWriter = response.getWriter();
            printWriter.print(data);
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            if (null != printWriter) {
                printWriter.flush();
                printWriter.close();
            }
        }
    }

    public String getUuid(UserinfoService userinfoService, String account) {
        String uuid = null;
        Userinfo userinfo = userinfoService.getUserinfo(account);
        if (userinfo == null) {
            uuid = "";
        } else {
            uuid = userinfo.getUuid();
        }
        return uuid;
    }
}
